<template>
	<div class="w-1/2 pb-2 pr-2">
		<div class="bg-white w-full flex flex-col">
			<div class="pl-4 pt-4">员工流动图</div>
			<t-divider></t-divider>
			<div class="pl-4 pr-4 pb-4 flex-grow">
				<div class="flex flex-col">
					<!-- 下拉菜单 -->
					<t-dropdown class="ml-auto" :options="options" @click="clickHandler" :minColumnWidth="88">
						<t-button theme="default" variant="outline">{{year.content}}</t-button>
					</t-dropdown>
					<div class="overflow-hidden" id="myChart" style="width: 40vw; height: 40vh"></div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import { toYear } from '@/unit/myDate'
	import '@/unit/walden'

	export default {
		name: 'UserData',
		data() {
			return {
				sourceArr: [],
				seriesArr: [],
				year: {
					content: '',
					value: ''
				}
			}
		},
		computed: {
			options() {
				let arr = []
				for (let i = 0; i < 5; i++) {
					arr[i] = {}
					arr[i].content = (toYear() - i) + '年'
					arr[i].value = toYear() - i
				}
				return arr
			}
		},
		methods: {
			// 选择框
			clickHandler(data) {
				this.year.content = data.content
				this.year.value = data.value
				this.getUserData(this.year.value)
			},
			// 封装发送请求并处理数据渲染图表
			getUserData(year) {
				this.$store.dispatch('dashboard/UserData', year).then(res => {
					for (let i = 0; i < res.data.length; i++) {
						this.sourceArr[i] = []
					}
					for (let i = 0; i < res.data.length; i++) {
						this.sourceArr[i].push(res.data[i][0].day_date)
						for (let j = 0; j < res.data[i].length; j++) {
							this.sourceArr[i].push(parseFloat(res.data[i][j].total_number))
						}
					}
					let arr = []
					for (let i = 0; i < res.data[0].length; i++) {
						arr[i] = res.data[0][i].department_name
						this.seriesArr[i] = {}
						this.seriesArr[i].type = 'bar'
					}
					arr.unshift('product')
					this.sourceArr.unshift(arr)
					this.drawLine();
				})
			},
			// 封装图表插件
			drawLine() {
				// 基于准备好的dom，初始化echarts实例
				let myChart = this.$echarts.init(document.getElementById('myChart'), 'walden')
				// 绘制图表
				myChart.setOption({
					legend: {
						type: 'scroll',
						orient: 'vertical',
						right: 10,
						top: 'center'
					},
					tooltip: {
						trigger: 'axis'
					},
					dataset: {
						source: this.sourceArr
					},
					xAxis: {
						type: 'category'
					},
					yAxis: {},
					series: this.seriesArr
				});
				// 自动调整容器大小
				window.onresize = function() {
					myChart.resize();
				};
			}
		},
		mounted() {
			this.year.content = this.options[0].content
			this.year.value = this.options[0].value
			// 组件创建后发送请求
			this.getUserData(this.year.value)
		},
	}
</script>